const mongoose = require('mongoose');

function checkEmpty(word){
    if(word){
        return (typeof word)=='string' && word.length>0;
    }
    return false;
}

var en_word = mongoose.Schema({
    word:{type:String,index:true,required:true},
    star:{type:Number,default:1},
    classtime:{type:Number,default:0},
    success:{type:Boolean,default:false},
    synonym:[String],
    antonym:[String],
    recordtime:{type:Date,default:new Date()},
    remarks:[String],
    explanations:[
        {
            property:String,
            explanation:String
        }
    ],
    etymas:[{type:mongoose.Schema.Types.ObjectId,ref:'etyma'}],
    sentence:[String],
    phrase:[String]
});
en_word.path('word').validate(checkEmpty,'word is not a valid string');
en_word.virtual('annotation').get(function(){
    let obj=this.explanations.map(item=>item.property+'. '+item.explanation);
    return obj;
});
var etymaschema = mongoose.Schema({
    etyma:{type:String,index:true},
    lv:{type:Number,default:1},
    explanation:String,
    eg:[String],
    recordtime:{type:Date,default:new Date()},
    remarks:[String]
});
etymaschema.virtual('en_words',{
    ref:'en_word',
    localField:'_id',
    foreignField:'etymas',
    justOn:false
});

var managerSchema = mongoose.Schema({
	username:{type:String,required:true,unique:true},
	userpassword:{type:String,minlength:8,required:true},
	recordtime:{type:Date,default:new Date()},
	powermask:{type:Number,enum:[1000,2000,3000,4000],default:1000},
	uid:{type:String,unique:true,required:true,index:true},
	note:{type:String,default:'管理员说明'}
});

var managermodel = mongoose.model('manager',managerSchema);
var etymamodel = mongoose.model('etyma',etymaschema);
var en_wordmodel = mongoose.model('en_word',en_word);

module.exports = {
    wordmodel:en_wordmodel,
    etymamodel:etymamodel,
	managermodel:managermodel
};
